package com.car.rental.user.service.impl;

import com.car.rental.common.core.exception.BusinessException;
import com.car.rental.common.core.response.ResponseResult;
import com.car.rental.user.constant.DriverLicenseStatus;
import com.car.rental.user.entity.DriverLicense;
import com.car.rental.user.mapper.DriverLicenseMapper;
import com.car.rental.user.model.request.DriverLicenseRequest;
import com.car.rental.user.model.response.DriverLicenseResponse;
import com.car.rental.user.service.DriverLicenseService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DriverLicenseServiceImpl implements DriverLicenseService {

    private final DriverLicenseMapper driverLicenseMapper;

    @Value("${upload.base-path}")
    private String basePath;
    
    @Value("${upload.paths.license}")
    private String licensePath;
    
    private static final Logger log = LoggerFactory.getLogger(DriverLicenseServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> submitLicense(Long userId, DriverLicenseRequest request) {
        // 检查驾驶证号是否已被使用
        DriverLicense existLicense = driverLicenseMapper.selectByLicenseNumber(request.getLicenseNumber());
        if (existLicense != null) {
            throw new BusinessException("该驾驶证号已被使用");
        }

        // 验证有效期
        if (request.getExpireDate().isBefore(LocalDate.now())) {
            throw new BusinessException("驾驶证已过期");
        }

        // 创建新的驾驶证记录
        DriverLicense license = new DriverLicense();
        BeanUtils.copyProperties(request, license);
        license.setUserId(userId);
        license.setStatus(DriverLicenseStatus.PENDING.getCode());
        license.setRemark(DriverLicenseStatus.PENDING.getRemark());

        driverLicenseMapper.insert(license);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult<List<DriverLicenseResponse>> getLicenseInfo(Long userId) {
        List<DriverLicense> licenses = driverLicenseMapper.selectListByUserId(userId);
        
        List<DriverLicenseResponse> responseList = licenses.stream()
            .map(license -> {
                DriverLicenseResponse response = new DriverLicenseResponse();
                BeanUtils.copyProperties(license, response);
                return response;
            })
            .collect(Collectors.toList());
        
        return ResponseResult.success(responseList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> updateLicenseStatus(Long userId, String licenseNumber, Integer status, String remark) {
        // 验证状态是否有效
        String defaultRemark = DriverLicenseStatus.getRemarkByCode(status);
        if (defaultRemark == null) {
            throw new BusinessException("无效的状态码");
        }
        
        // 不允许修改为认证中状态
        if (status.equals(DriverLicenseStatus.PENDING.getCode())) {
            throw new BusinessException("不允许手动设置为认证中状态");
        }
        
        DriverLicense driverLicense = new DriverLicense();
        driverLicense.setUserId(userId);
        driverLicense.setLicenseNumber(licenseNumber);
        driverLicense.setStatus(status);
        driverLicense.setRemark(StringUtils.hasText(remark) ? remark : defaultRemark);
        
        driverLicenseMapper.updateByUserIdAndLicenseNumber(driverLicense);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult<Boolean> checkLicenseVerified(Long userId) {
        List<DriverLicense> licenses = driverLicenseMapper.selectListByUserId(userId);
        // 只要有一个驾驶证通过认证即可
        boolean verified = licenses.stream().anyMatch(license -> license.getStatus() == 2);
        return ResponseResult.success(verified);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> updateLicense(Long userId, DriverLicenseRequest request) {
        // 1. 获取原驾驶证信息
        List<DriverLicense> licenses = driverLicenseMapper.selectListByUserId(userId);
        DriverLicense oldLicense = licenses.stream()
            .filter(license -> license.getLicenseNumber().equals(request.getLicenseNumber()))
            .findFirst()
            .orElseThrow(() -> new BusinessException("驾驶证信息不存在"));
        
        // 2. 如果有新图片，删除旧图片
        if (!oldLicense.getImageUrl().equals(request.getImageUrl())) {
            // 从旧图片URL中提取文件名
            String oldFileName = oldLicense.getImageUrl().substring(oldLicense.getImageUrl().lastIndexOf("/") + 1);
            // 删除旧文件
            String oldFilePath = basePath + licensePath + oldFileName;
            new File(oldFilePath).delete();
        }
        
        // 3. 更新驾驶证信息
        DriverLicense license = new DriverLicense();
        BeanUtils.copyProperties(request, license);
        license.setUserId(userId);
        
        driverLicenseMapper.updateByUserId(license);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult<String> uploadLicenseImage(Long userId, MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                throw new BusinessException("文件名不能为空");
            }
            
            String fileName = UUID.randomUUID().toString() + 
                originalFilename.substring(originalFilename.lastIndexOf("."));
            
            File targetFile = new File(basePath + licensePath + fileName);
            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);
            
            return ResponseResult.success("/user/uploads/license/" + fileName);
        } catch (Exception e) {
            log.error("上传驾驶证照片失败", e);
            throw new BusinessException("上传驾驶证照片失败: " + e.getMessage());
        }
    }

    @Override
    public ResponseResult<List<DriverLicenseResponse>> getAllLicenses() {
        List<DriverLicense> licenses = driverLicenseMapper.selectList(null);
        
        List<DriverLicenseResponse> responseList = licenses.stream()
            .map(license -> {
                DriverLicenseResponse response = new DriverLicenseResponse();
                BeanUtils.copyProperties(license, response);
                return response;
            })
            .collect(Collectors.toList());
        
        return ResponseResult.success(responseList);
    }
} 